package uk.co.agileworks.bidpirate.service;

import java.util.List;

import uk.co.agileworks.bidpirate.model.Bid;

public class Pager {

	private static final int RESULTS_PER_PAGE = 5;

	private final List<Bid> bids;
	private int currentPage;

	public Pager(List<Bid> bids) {
		this.bids = bids;
	}

	public int firstResultOnPage() {
		return (currentPage - 1) * RESULTS_PER_PAGE;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public String getHtml() {
		StringBuffer html = new StringBuffer(128);
		html.append("<a href='listBids.html?page=");
		html.append(prevPage());
		html.append("'>&lt;</a>\n");
		for (int page = 1; page <= lastPage(); page++) {
			if (currentPage == page) {
				html.append("<u>");
				html.append(page);
				html.append("</u>\n");
			} else {
				html.append("<a href='listBids.html?page=");
				html.append(page);
				html.append("'>");
				html.append(page);
				html.append("</a>\n");
			}
		}
		html.append("<a href='listBids.html?page=");
		html.append(nextPage());
		html.append("'>&gt;</a>\n");
		return html.toString();
	}

	public List<Bid> getPageResults() {
		return bids.subList(firstResultOnPage(), lastResultOnPage() + 1);
	}

	public int lastPage() {
		return (bids.size() - 1) / RESULTS_PER_PAGE + 1;
	}

	public int lastResultOnPage() {
		int lastResultOnPage = currentPage * RESULTS_PER_PAGE - 1;
		return lastResultOnPage < bids.size() - 1 ? lastResultOnPage : bids.size() - 1;
	}

	public int nextPage() {
		return currentPage + 1 > lastPage() ? lastPage() : currentPage + 1;
	}

	public int prevPage() {
		return currentPage - 1 < 1 ? 1 : currentPage - 1;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage < lastPage() ? currentPage : lastPage();
	}

}
